package mt.comm;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Allows listener to run in a background thread
 *
 */
class ServerListener implements Runnable {
	private ConcurrentHashMap<String, Socket> clientMap;
	private Queue<ServerSideMessage> queue;
	private ServerSocket serverSocket;
	private int numberOfDispatcherThreads;

	/**
	 * @param clientMap
	 *            A HashMap with all the clients
	 * @param queue
	 *            A queue with all the messages
	 * @param serverSocket
	 *            The server socket
	 * @param numberOfDispatcherThreads
	 *            The number of threads in the thread pool
	 */
	public ServerListener(ConcurrentHashMap<String, Socket> clientMap,
			Queue<ServerSideMessage> queue, ServerSocket serverSocket,
			int numberOfDispatcherThreads) {
		super();
		this.clientMap = clientMap;
		this.queue = queue;
		this.serverSocket = serverSocket;
		this.numberOfDispatcherThreads = numberOfDispatcherThreads;
	}

	@Override
	public void run() {
		// --- Listening and dispatching all requests -------------------------
		Socket fromClient = null;
		while (true) {
			// --- Waiting for a request --------------------------------------
			try {
				fromClient = serverSocket.accept();
			} catch (IOException e) {
			}
			// --- Calling the dispatcher -------------------------------------
			ExecutorService executor = Executors
					.newFixedThreadPool(numberOfDispatcherThreads);
			executor.execute(new ClientWorker(clientMap, queue, fromClient));
		}
	}
}